package cn.yunhe.listener;

import cn.yunhe.entity.User;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;
import java.util.HashSet;
import java.util.Set;

@WebListener
public class OnlineUserListener implements ServletContextListener,HttpSessionListener,HttpSessionAttributeListener {

    ServletContext application;
    //tomcat启动
    @Override
    public void contextInitialized(ServletContextEvent sc) {

        //创建集合,用来存放在线用户
        Set<User> onlineUsers = new HashSet<User>();
        application= sc.getServletContext();
        application.setAttribute("onlineUsers",onlineUsers);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sc) {

    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent hsb) {
        HttpSession session = hsb.getSession();
        User user =(User) session.getAttribute("Curr_User");
        Set<User> onlineUsers = (Set<User>) application.getAttribute("onlineUsers");
        if (user!=null) {
            onlineUsers.add(user);
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent hsb) {

        User user = (User) hsb.getValue();

        Set<User> onlineUsers = (Set<User>) application.getAttribute("onlineUsers");

        onlineUsers.remove(user);
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent hse) {

    }

    @Override
    public void sessionCreated(HttpSessionEvent hse) {

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent hse) {
        HttpSession session = hse.getSession();
        User user =(User) session.getAttribute("Curr_User");
        Set<User> onlineUsers = (Set<User>) application.getAttribute("onlineUsers");
        onlineUsers.remove(user);
    }
}
